<template>

  <div style="padding: 30px">
    <div>
      <el-row :gutter="15">
        <el-form ref="elForm" :model="formData" :rules="rules" size="medium" label-width="100px"
                 label-position="left">
          <el-col v-if="!isStore" :span="8">
            <el-form-item label="请选择店铺">
              <el-select v-model="formData.shopId" placeholder="请选择">
                <el-option
                  v-for="item in store"
                  :key="item.shopsId"
                  :label="item.shopName"
                  :value="item.shopsId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col v-if="isStore" :span="8">
            <el-form-item label="店铺" prop="formData.shopId" :disabled="true">
              <el-input v-model="aStore.shopName" placeholder="店铺编号" clearable
                        :style="{width: '100%'}"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label-width="-1px" label="" prop="field104">
              <el-button type="primary" icon="el-icon-search" size="small">搜索</el-button>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="商品编号" prop="proNumber">
              <el-input v-model="formData.proNumber" placeholder="商品编号" clearable
                        :style="{width: '100%'}"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label-width="-1px" label="" prop="field104">
              <el-button type="primary" icon="el-icon-search" size="small">搜索</el-button>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品名称" prop="proName">
              <el-input v-model="formData.proName" type="textarea" placeholder="请输入商品名称"
                        :autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品描述" prop="productDescribe">
              <el-input v-model="formData.productDescribe" type="textarea" placeholder="请输入商品描述商品描述商品描述商品描述"
                        :autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品分类" prop="sortId">
              <el-cascader v-model="formData.sortId" :options="category" :props="sortIdProps"
                           :style="{width: '100%'}" :show-all-levels="false" placeholder="请选择商品分类" filterable clearable>
              </el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品品牌" prop="brandId">
              <el-select v-model="formData.brandId" placeholder="请选择">
                <el-option
                  v-for="item in brand"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="价格" prop="price">
              <el-input v-model="formData.price" placeholder="请输入价格" clearable :style="{width: '100%'}">
                <template slot="prepend">￥</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="总数量" prop="allCount">
              <el-input-number v-model="formData.allCount" placeholder="总数量" controls-position=right>
              </el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="首页商品图片" prop="image">
              <image-upload v-model="formData.image"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品状态" prop="status" required>
              <el-switch v-model="formData.status" active-text="上架" inactive-text="下架" inactive-color="#4F4F4F">
              </el-switch>
            </el-form-item>
          </el-col>
          <!-- 分割线 -->

          <el-col :span="24">
            <hr/>
            <el-button style="margin-top: 20px" type="primary" plain @click="clickTag">点击添加参数</el-button>
          </el-col>

          <el-col :span="24">
            <edit-args :drawer="drawer" @toApp="drawerData" @closeArgsDrawer="closeArgsDrawer"/>
          </el-col>

          <el-col :span="24">
            <div v-if="productArgs.length !== 0">
              <div v-for="(item, index) in productArgs" :key="index" style="margin-top: 20px">
                <b>参数 {{ index + 1 }} -> ({{ item.argName }})</b>
                <el-button @click="deleteArgs(index)" style="margin-left: 10px" type="danger" size="mini">删除</el-button>
                <el-table v-if="item.allProperty.length !== 0" :data="item.allProperty">
                  <el-table-column property="name" label="属性名" width="150"></el-table-column>
                  <el-table-column property="price" label="价格" width="200"></el-table-column>
                  <el-table-column property="stock" label="库存"></el-table-column>
                  <el-table-column property="description" label="描述" :show-overflow-tooltip="true"></el-table-column>
                  <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                    <template v-slot="scope">
                      <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-edit"
                        @click="handleUpdate(item.argName, scope.row)"
                        v-hasPermi="['product:product:edit']"
                      >修改
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </el-col>


          <el-col style="margin-top: 20px" :span="24">
            <hr/>
            <el-button style="margin-top: 20px" type="primary" plain @click="clickAddImage">点击添加图片</el-button>
          </el-col>

          <el-col :span="24">
            <edit-image :image-drawer="imageDrawer" @imageDrawerData="imageDrawerData"
                        @closeImageDrawer="closeImageDrawer"/>
          </el-col>

          <el-col :span="24">
            <div style="margin-top: 30px">
              <div style="margin-top: 30px; margin-bottom: 30px"><b>轮播图</b></div>
              <el-image
                v-for="item in allImage.swiperImage"
                style="width: 100px; height: 100px; margin-left: 5px"
                :src="item"
                fit="fill"></el-image>

              <div style="margin-top: 30px; margin-bottom: 30px"><b>详情图</b></div>
              <el-image
                v-for="item in allImage.detailImage"
                style="width: 100px; height: 100px; margin-left: 5px"
                :src="item"
                fit="fill"></el-image>
            </div>
          </el-col>

          <el-col :span="24">
            <hr/>
            <el-form-item size="large" style="margin-top: 20px">
              <el-button type="primary" @click="submitForm">提交</el-button>
              <el-button @click="resetForm">重置</el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
    </div>

    <!--  弹出框 修改属性  -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="argItem" label-width="90px">
        <el-form-item label="商品参数" prop="argName" disabled="">
          <el-input v-model="argItem.argName" placeholder="请输入商品参数"/>
        </el-form-item>
        <el-form-item label="属性名" prop="name">
          <el-input v-model="argItem.name" placeholder="请输入参数属性"/>
        </el-form-item>
        <el-form-item label="总数量" prop="stock">
          <el-input-number v-model="argItem.stock" placeholder="总数量" controls-position=right>
          </el-input-number>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model="argItem.price" placeholder="请输入价格" clearable :style="{width: '100%'}">
            <template slot="prepend">￥</template>
          </el-input>
        </el-form-item>
        <el-form-item label="商品描述" prop="productDescribe">
          <el-input v-model="argItem.description" type="textarea" placeholder="请输入商品描述"
                    :autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}"></el-input>
        </el-form-item>
        <div>
          <el-button size="small" type="primary" @click="submitFormArg">确 定</el-button>
          <el-button size="small" @click="open=false">取 消</el-button>
        </div>
      </el-form>
    </el-dialog>

  </div>


</template>
<script>
import EditArgs from "./editArgs";
import EditImage from "./editImage";
import {addProductAll, queryProductById} from "../../../../api/product/product";
import {getBrand, listBrand} from "../../../../api/product/brand";
import {listCategories} from "../../../../api/product/categories";
import {getAllByProId} from "../../../../api/product/args";
import {listImage} from "../../../../api/product/image";
import {listShop} from "../../../../api/shop/shop";

export default {
  components: {EditImage, EditArgs},
  data() {
    return {
      drawer: false,    // 打开参数编辑的抽屉页面
      productArgs: [],  // 存放商品的所有参数
      args: [],
      isStore: false,
      aStore: null,

      myArray: [3, 5, 7, 2, 1, 0],

      imageDrawer: false, // 打开图片编辑的抽屉页面
      allImage: {
        swiperImage: [],
        detailImage: [],
      },       // 存放所有图片
      category: [], // 分类
      brand: [], // 品牌

      open: false, // 控制修改属性的弹出框
      argItem: {},
      title: '',
      store: [],
      storeId: null,


      formData: {
        proId: null,
        shopId: null,
        field104: undefined,
        proNumber: undefined,
        field106: undefined,
        proName: undefined,
        sortId: [],
        brandId: undefined,
        productDescribe: undefined,
        price: undefined,
        allCount: undefined,
        status: true,
        image: undefined,
      },
      rules: {
        proNumber: [{
          required: true,
          message: '商品编号',
          trigger: 'blur'
        }],
        proName: [{
          required: true,
          message: '请输入商品名称',
          trigger: 'blur'
        }],
        sortId: [{
          required: true,
          type: 'array',
          message: '请至少选择一个sortId',
          trigger: 'change'
        }],
        brandId: [{
          required: true,
          message: '请选择商品品牌',
          trigger: 'change'
        }],
        productDescribe: [{
          required: true,
          message: '请输入商品描述商品描述商品描述商品描述',
          trigger: 'blur'
        }],
        price: [{
          required: true,
          message: '请输入价格',
          trigger: 'blur'
        }, {
          pattern: /^(\d+(\.\d{1,2})?)$/,
          message: '请按要求输入价格',
          trigger: 'blur'
        }],
        allCount: [{
          required: true,
          message: '总数量',
          trigger: 'blur'
        }],
      },

      sortIdProps: {
        "multiple": false,
        label: "name",
        children: "children",
        value: "id"
      },
    }
  },
  computed: {},
  watch: {},
  created() {

    let proId = this.$route.query.proId;
    if (this.$route.query.shopId!==undefined) {
      this.storeId = this.$route.query.shopId
      console.info(this.storeId)
    }

    if ('0' !== proId) {
      this.loadData(proId)
      this.loadDataOfNew();
    } else {
      this.loadDataOfNew();
    }
  },

  methods: {
    /* ==== 以下关于子组件（图片 image）部分 开始 ====*/
    clickAddImage() {
      this.imageDrawer = true;
    },
    imageDrawerData(data) {
      this.allImage.detailImage = data.detailImage;
      this.allImage.swiperImage = data.swiperImage;
      this.imageDrawer = false;
    },
    closeImageDrawer() {
      this.imageDrawer = false;
    },
    /* ==== 以上关于子组件 结束 ====*/

    /* ===== 以下关于子组件（参数 args）部分 开始 ==== */
    clickTag() {
      this.drawer = true;
    },
    drawerData(data) {
      this.drawer = false;
      this.productArgs.push(data[0]);
    },
    closeArgsDrawer() {
      this.drawer = false
    },
    /* ===== 以上关于子组件 结束 ==== */


    /* ============ 以下为本页面相关的 ============ */
    // 参数修改
    handleUpdate(argName, row) {
      this.argItem = row
      this.argItem.argName = argName
      this.open = true
      this.title = "修改参数"
    },
    // 参数删除
    deleteArgs(index) {
      this.$modal.confirm('是否确认删除').then(() => {
        let item = this.productArgs
        this.productArgs = []
        item.forEach((v, i)=>{
          if (i !== index) {
            this.productArgs.push(v)
          }
        })
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },

    // 提交修改的参数
    submitFormArg() {
      this.productArgs.forEach((item)=>{
        if (item.argName===this.argItem.argName) {
          item = this.argItem
        }
      })
      this.$modal.msgSuccess("操作成功")
      this.open = false
    },

    // 初始加载数据
    async loadData(proId) {
      // 根据商品 id 查商品数据 (商品 分类 详情 品牌）
      let data = await queryProductById(proId)
      let product = data.data;
      this.formData.proId = product.proId;
      this.formData.shopId = product.shopId;
      this.formData.proNumber = product.proNumber;
      this.formData.proName = product.proName;
      this.formData.productDescribe = product.detail.productDescribe;
      this.formData.price = product.proPrice;
      this.formData.allCount = product.detail.allCount;
      this.formData.status = product.status === '1';
      this.formData.image = product.image;

      // 查询所有的品牌
      // let brandData = await listBrand()
      // let brand = brandData.rows;
      let bd = await getBrand(product.brandId);
      this.formData.brandId = bd.data.id;

      // 查询所有的分类
      let categoryData = await listCategories();
      let category = categoryData.data;
      // 处理分类id做回显
      let cyId = product.sortId;
      let cyPid = ''; // 根据该分类id，找其上一级id
      category.forEach((c) => {
        if (c.id === cyId) {
          cyPid = c.parentId;
        }
      });
      category.forEach((c) => {
        if (cyPid === c.id) {
          this.formData.sortId.push(c.parentId);
        }
      })
      this.formData.sortId.push(cyPid);
      this.formData.sortId.push(cyId); // 上面这几个主要是找到商品的各级分类，然后做回显
      this.category = this.handleTree(category, "id", "parentId");

      // 查对应的参数 查到该商品的所有参数
      let argsData = await getAllByProId(proId);
      let args = argsData.data;
      let aps = args.filter(a => {
        return a.parentId === 0
      })
      aps.forEach((ap) => {
        let list = [];
        args.forEach((t) => {
          if (ap.id === t.parentId) {
            list.push(t)
          }
        })
        let item = {
          argName: ap.name,
          allProperty: list
        }
        this.productArgs.push(item);
      })

      // 查所有的图片
      let imageData = await listImage({productId: proId})
      let imageAll = imageData.rows;
      imageAll.forEach((i) => { // 0 - 轮播图 1 - 详情图
        if (i.imgType === '0') {
          this.allImage.swiperImage.push(i.imgUrl);
        } else if (i.imgType === '1') {
          this.allImage.detailImage.push(i.imgUrl);
        }
      })


    },
    async loadDataOfNew() {
      // 查询所有的分类
      let categoryData = await listCategories();
      let category = categoryData.data;
      this.category = this.handleTree(category, "id", "parentId");
      // 查询所有品牌
      let brandData = await listBrand();
      this.brand = brandData.rows;
      // 查询所有店铺
      let store = await listShop({})
      if (this.storeId === null) {
        this.isStore = false
        this.store = store.rows
      } else {
        this.isStore = true
        this.aStore = store.rows.filter(o=>o.shopsId==this.storeId)[0]
      }
    },

    submitForm() {
      this.$refs['elForm'].validate(valid => {
        // this.handleData()
        if (!valid) return
        // 处理数据，包装为后端接口需要的类型
        if (this.aStore!==null) {
          this.formData.shopId = this.aStore.shopsId
        }
        addProductAll(this.handleData()).then(re => {
          this.$modal.msgSuccess("操作成功");
          this.$tab.closeOpenPage({path: "/product/product"})
          this.resetForm();
        })
      })
    },
    resetForm() {
      this.productArgs = [];
      this.allImage = {};
      this.$refs['elForm'].resetFields()
    },
    // 处理数据
    handleData() {
      // 商品
      let sort = this.formData.sortId;
      let category = sort[0] + "/" + sort[1] + "/" + sort[2]
      console.info("0000")
      console.info(this.formData)
      let product = {
        proId: this.formData.proId,
        proNumber: this.formData.proNumber,
        proPrice: this.formData.price,
        proName: this.formData.proName,
        sortId: this.formData.sortId[this.formData.sortId.length - 1],
        shopId: this.formData.shopId,
        status: this.formData.status ? '1' : '0',
        brandId: this.formData.brandId,
        image: this.formData.image,
        category: category,
      };
      // 商品详情
      let detail = {
        productDescribe: this.formData.productDescribe,
        allCount: this.formData.allCount,
      };
      // 图片列表
      let image = [];
      this.allImage.swiperImage.forEach(s => {
        let img = {
          imgUrl: s,
          imgType: '0'
        }
        image.push(img)
      })
      this.allImage.detailImage.forEach(d => {
        let img = {
          imgUrl: d,
          imgType: '1'
        }
        image.push(img)
      })
      // 商品参数
      // let args = []

      this.productArgs.forEach(pa => {
        let arg = {}
        arg.name = pa.argName;
        arg.parentId = 0;
        arg.price = null;
        arg.stock = null;
        arg.description = null;
        arg.image = null;
        this.args.push(arg);
        console.info("pa --> " + arg.name + arg.parentId + arg.price + arg.description)
        pa.allProperty.forEach(item => {
          let arg = {}
          arg.name = item.name;
          arg.parentId = null;
          arg.price = item.price;
          arg.stock = item.stock;
          arg.description = item.description;
          arg.image = item.image;
          this.args.push(arg);
          console.info("item --> " + arg.name + arg.parentId + arg.price + arg.description)
        })
      })
      return {
        product: product,
        detail: detail,
        args: this.args,
        prodImage: image,
      };
    }
  }
}

</script>
<style>

</style>
